package com.stupidzhe.vbreview.controller.adm;

import com.stupidzhe.vbreview.bean.ResultBean;
import com.stupidzhe.vbreview.domain.Class;
import com.stupidzhe.vbreview.domain.Teacher;
import com.stupidzhe.vbreview.service.ClassService;
import com.stupidzhe.vbreview.service.TeacherBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/adm/class")
public class AdmClassController {


    private final ClassService classService;

    public AdmClassController(ClassService classService) {
        this.classService = classService;
    }

    @RequestMapping(value = "/")
    public String mainView(@RequestParam(defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(required = false) String keyword, Model model, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        model.addAttribute("pageBean", classService.getClassByPage(pageNum, teacher.getUserId(), keyword));
        model.addAttribute("keyword", keyword);
        return "adm/adm.class";
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addView() {
        return "adm/adm.class.add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean add(@RequestParam(value = "className") String className, HttpServletRequest request) {
        Teacher teacher = (Teacher) request.getAttribute("teacher");
        return classService.addClass(className.trim(), teacher);
    }

    @RequestMapping(value = "/{id}")
    public String detail(@PathVariable(value = "id") Integer classId, Model model) {
        Class c = classService.selectClass(classId);
        model.addAttribute("class", c);
        return "adm/adm.class.detail";
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResultBean edit(@PathVariable(value = "id") Integer classId, @RequestParam(value = "className") String className) {
        return classService.editClass(classId, className);

    }
}
